package com.example.test.operate.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      sql帮助类
 * </desc>
 *
 * @createDate 2017/9/13
 */
public class SqlUtil {

    protected static final Logger LOG = LoggerFactory.getLogger(DataAccessException.class);


    /**
     * <desc>
     *      将实体类转换为map格式的param
     * </desc>
     *
     * @param obj 待转换的bean
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/21
     */
    public static <T> Map<String, Object> convertBeanToMapParams(T obj) throws Exception {
        Map<String, Object> beanMap = new HashMap<>();
        try {
            putDeclaredFieldsToMap(obj, obj.getClass(), beanMap);

        } catch (Exception e) {
            throw new Exception("将实体转换为map格式的param异常！", e);
        }
        return beanMap;
    }

    /**
     * <desc>
     *      将某一对象所有声明字段放入map中（包括父类声明的字段）
     * <desc/>
     *
     * @param obj 实例对象
     * @param clazz 实例对象的类对象或其父类对象
     * @param beanMap map对象，外部传入
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-19
     */
    private static void putDeclaredFieldsToMap(Object obj, Class clazz, Map beanMap) throws Exception {
        //先解析子类的参数
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            //获取get属性方法名
            String name = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            //获取属性的类型
            String type = field.getGenericType().toString();
            Object value;
            Method m = obj.getClass().getMethod("get" + name);
            value = m.invoke(obj);
            if (type.equals("class java.lang.String")) {
                //调用getter方法获取属性值
                beanMap.put(field.getName(), StringHandlerUtil.getStringOrNull((String) value));
            }else{
                if (type.equals("class java.util.Date")) {
                    beanMap.put(field.getName(), value != null && !value.toString().equals("") ?
                            StringHandlerUtil.getStringOrNull(DateUtil.fomatDate((Date) value)) : null);
                } else {
                    beanMap.put(field.getName(), value != null && !value.toString().equals("") ? value : null);
                }
            }
        }
        //继续解析其父类参数
        if (null != clazz.getSuperclass() && !Object.class.equals(clazz.getSuperclass())){
            putDeclaredFieldsToMap(obj, clazz.getSuperclass(), beanMap);
        }
    }



}
